package neatlogic.module.change.api;

import neatlogic.framework.auth.core.AuthAction;
import neatlogic.framework.change.constvalue.*;
import neatlogic.framework.common.constvalue.ApiParamType;
import neatlogic.framework.crossover.CrossoverServiceFactory;
import neatlogic.framework.process.auth.PROCESS_BASE;
import neatlogic.framework.process.crossover.IProcessStepHandlerCrossoverUtil;
import neatlogic.framework.process.dto.ProcessTaskStepVo;
import neatlogic.framework.process.exception.process.ProcessStepHandlerNotFoundException;
import neatlogic.framework.process.stephandler.core.IProcessStepInternalHandler;
import neatlogic.framework.process.stephandler.core.ProcessStepInternalHandlerFactory;
import neatlogic.framework.restful.annotation.Description;
import neatlogic.framework.restful.annotation.Input;
import neatlogic.framework.restful.annotation.OperationType;
import neatlogic.framework.restful.annotation.Param;
import neatlogic.framework.restful.constvalue.OperationTypeEnum;
import neatlogic.framework.restful.core.privateapi.PrivateApiComponentBase;
import neatlogic.module.change.dao.mapper.ChangeMapper;
import neatlogic.framework.change.dto.ChangeStepVo;
import neatlogic.framework.change.dto.ChangeVo;
import neatlogic.framework.change.dto.ProcessTaskStepChangeVo;
import neatlogic.framework.change.exception.ChangeHandleHasNotStartedException;
import neatlogic.framework.change.exception.ChangeNoPermissionException;
import neatlogic.framework.change.exception.ChangeStepNotFoundException;
import neatlogic.module.change.service.ChangeService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@AuthAction(action = PROCESS_BASE.class)
@OperationType(type = OperationTypeEnum.OPERATE)
public class ChangeStepCompleteApi extends PrivateApiComponentBase {

    @Autowired
    private ChangeMapper changeMapper;

    @Autowired
    private ChangeService changeService;

    @Override
    public String getToken() {
        return "change/step/complete";
    }

    @Override
    public String getName() {
        return "nmca.changestepcompleteapi.getname";
    }

    @Override
    public String getConfig() {
        return null;
    }

    @Input({
            @Param(name = "changeStepId", type = ApiParamType.LONG, isRequired = true, desc = "term.change.changestepid"),
            @Param(name = "content", type = ApiParamType.STRING, desc = "common.content"),
            @Param(name = "source", type = ApiParamType.STRING, desc = "common.source")
    })
    @Description(desc = "nmca.changestepcompleteapi.getname")
    @Override
    public Object myDoService(JSONObject jsonObj) throws Exception {
        Long changeStepId = jsonObj.getLong("changeStepId");
        ChangeStepVo changeStep = changeMapper.getChangeStepById(changeStepId);
        if (changeStep == null) {
            throw new ChangeStepNotFoundException(changeStepId);
        }
        /** 获取当前变更锁 **/
        changeMapper.getChangeLockById(changeStep.getChangeId());
        ChangeVo changeVo = changeMapper.getChangeById(changeStep.getChangeId());
        changeService.getChangeStepDetail(changeStep);
        if (!changeService.isCompletableChangeStep(changeVo, changeStep)) {
            throw new ChangeNoPermissionException(ChangeOperationType.COMPLETECHANGESTEP.getText());
        }
        /** 完成变更步骤时，将变更步骤状态设置为“已成功” **/
        changeStep.setStatus(ChangeStatus.SUCCEED.getValue());
        changeMapper.updateChangeStepStatus(changeStep);

        /** 完成当前变更步骤时，触发激活其他变更步骤 **/
        changeService.activeChangeStep(changeStep.getChangeId());

        /** 完成变更步骤时，触发更新processtask_step_worker和processtask_step_user数据 **/
        ProcessTaskStepChangeVo processTaskStepChangeVo = changeMapper.getProcessTaskStepChangeHandleByChangeId(changeStep.getChangeId());
        if (processTaskStepChangeVo == null) {
            throw new ChangeHandleHasNotStartedException();
        }
        IProcessStepInternalHandler processStepUtilHandler = ProcessStepInternalHandlerFactory.getHandler(ChangeProcessStepHandlerType.CHANGEHANDLE.getHandler());
        if (processStepUtilHandler == null) {
            throw new ProcessStepHandlerNotFoundException(ChangeProcessStepHandlerType.CHANGEHANDLE.getHandler());
        }
        processStepUtilHandler.updateProcessTaskStepUserAndWorker(processTaskStepChangeVo.getProcessTaskId(), processTaskStepChangeVo.getProcessTaskStepId());

        /** 生成活动 **/
        ProcessTaskStepVo currentProcessTaskStepVo = new ProcessTaskStepVo();
        currentProcessTaskStepVo.setProcessTaskId(processTaskStepChangeVo.getProcessTaskId());
        currentProcessTaskStepVo.setId(processTaskStepChangeVo.getProcessTaskStepId());
        currentProcessTaskStepVo.getParamObj().put("changeStepName", changeStep.getName());
        currentProcessTaskStepVo.getParamObj().putAll(jsonObj);
        IProcessStepHandlerCrossoverUtil processStepHandlerCrossoverUtil = CrossoverServiceFactory.getApi(IProcessStepHandlerCrossoverUtil.class);
        processStepHandlerCrossoverUtil.audit(currentProcessTaskStepVo, ChangeAuditType.COMPLETECHANGESTEP);
        processStepHandlerCrossoverUtil.notify(currentProcessTaskStepVo, ChangeTriggerType.COMPLETECHANGESTEP);
        processStepHandlerCrossoverUtil.action(currentProcessTaskStepVo, ChangeTriggerType.COMPLETECHANGESTEP);

        /** 判断所有变更步骤是否都完成了 **/
        List<ChangeStepVo> changeStepList = changeMapper.getChangeStepListByChangeId(changeStep.getChangeId());
        if (CollectionUtils.isNotEmpty(changeStepList)) {
            for (ChangeStepVo changeStepVo : changeStepList) {
                if (!changeStepVo.getStatus().equals(ChangeStatus.SUCCEED.getValue()) && !changeStepVo.getStatus().equals(ChangeStatus.ABORTED.getValue())) {
                    return null;
                }
            }
            processStepHandlerCrossoverUtil.notify(currentProcessTaskStepVo, ChangeTriggerType.COMPLETEALLCHANGESTEP);
            processStepHandlerCrossoverUtil.action(currentProcessTaskStepVo, ChangeTriggerType.COMPLETEALLCHANGESTEP);
        }
        return null;
    }

}
